import React, { Component } from 'react'
import constant from "../loan-setting/constant";
import { Button, Form, Input, Switch, message, Radio, Popconfirm } from 'antd'
import { messages } from "share/common";
import SubjectService from 'containers/finance-setting/subject-sheet/subject.service'
import Selector from "components/selector";
import AdvancedTable from "components/advanced-table";
import ListSelector from "components/list-selector";
import { connect } from "react-redux";

@connect(mapStateToProps)
class SubjectDetailRule extends Component {

  onSelectChange = selectedRowKeys => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    const { selectedData } = this.state;
    if (selected) {
      selectedData.push(record.id);
    } else {
      selectedData.splice(selectedData.findIndex(item => item === record.id),1);
    }
    this.setState({ selectedData });
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    changeRows.map(changeRow => this.onSelectItem(changeRow, selected));
  };

  state = {
    saveLoading: false,
    rowSelection: {
      selectedRowKeys: [],
      onChange: this.onSelectChange,
      onSelect: this.onSelectItem,
      onSelectAll: this.onSelectAll
    },
    selectedData: [],
    deleteLoading: false,
    propsLoading: false
  };

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        const { record, id } = this.props.params, { close, loginUser, tenantInfo } = this.props;
        this.setState({ saveLoading: true });
        value.accountName = value.accountDesc;
        value.accountSetId = id;
        value.tenantId = tenantInfo.id;
        SubjectService.saveSubSubjectDetail(Object.assign(record, value), loginUser.userOID).then(() => {
          this.setState({ saveLoading: false }, () => {
            message.success(messages('common.operate.success')/*操作成功*/);
            close(true);
          });
        }).catch(e => {
          message.error(e.response.data.message);
          this.setState({ saveLoading: false });
        })
      }
    })
  };

  service = (page, size) => {
    const { record } = this.props.params;
    return SubjectService.getSubSubject({ page, size, parentAccountId: record.id })
  };

  columns = [
    { title: messages('finance-5.key45')/*科目代码*/, dataIndex: 'accountCode' },
    { title: messages('finance-5.key46')/*科目名称*/, dataIndex: 'accountName' },
    { title: messages('finance-5.key47')/*科目类型*/, dataIndex: 'accountTypeName' },
    { title: messages('common.operation')/*操作*/, dataIndex: 'operation',
      render: (text, record) => {
        return (<div>
          <Popconfirm onConfirm={() => this.deleteItem(record.id)} title={messages('common.confirm.delete')/*确定要删除吗？*/}>{/* 你确定要删除吗 */}
            <a>{messages('common.delete')/*删除*/}</a>
          </Popconfirm>
        </div>)
      }
    }
  ];

  deleteItem = id => {
    const { selectedData, rowSelection } = this.state;
    SubjectService.deleteSubSubject(id).then(() => {
      message.success(messages('common.operate.success')/*操作成功*/);
      selectedData.splice(selectedData.findIndex(item => item === id),1);
      rowSelection.selectedRowKeys = selectedData;
      this.setState({ selectedData, rowSelection });
      this.tabRef.getList();
    }).catch(e => {
      message.error(e.response.data.message)
    })
  };

  handleDelete = () => {
    const { selectedData, rowSelection } = this.state;
    this.setState({ deleteLoading: true });
    SubjectService.batchDelete(selectedData).then(() => {
      rowSelection.selectedRowKeys = [];
      this.setState({ deleteLoading: false, selectedData: [], rowSelection });
      message.success(messages('common.operate.success')/*操作成功*/);
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({ deleteLoading: false })
    })
  };

  handleAdd = () => {
    const { record } = this.props.params, { tenantInfo } = this.props;
    ListSelector.open({
      type: 'subjectSelectorItem',
      labelKey: 'accountName',
      extraParams: {
        parentAccountId: record.id,
        accountSetId:  record.accountSetId
      }
    }, this).then(data => {
      this.setState({ propsLoading: true });
      let params = data.map(item => { return { parentAccountId: record.id, subAccountId: item.subAccountId, tenantId: tenantInfo.id } });
      SubjectService.addSubSubject(params).then(() => {
        message.success(messages('common.operate.success')/*操作成功*/);
        this.setState({ propsLoading: false });
        this.tabRef.getList();
      }).catch(e => {
        message.error(e.response.data.message);
        this.setState({ propsLoading: false });
      });
    })
  };

  render() {
    const { formItemLayout } = constant;
    const { saveLoading, rowSelection, deleteLoading, propsLoading, selectedData } = this.state;
    const { close } = this.props, { record } = this.props.params;
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <Form className={'new-form'}>
          <h3 className='sub-title' style={{marginTop: '0'}}>{messages('finance-5.key24')/*基础信息*/}</h3>
          <Form.Item
            label={messages('common.column.status')/*状态*/}
            {...formItemLayout}
          >
            {getFieldDecorator("enabled", {
              rules: [{ required: true }],
              valuePropName: "checked",
              initialValue: record.hasOwnProperty('enabled') ? record.enabled : true
            })(
              <Switch>{messages('finance-5.key48')/*启用temp*/}</Switch>
            )}
          </Form.Item>
          <Form.Item
            {...formItemLayout}
            label={messages('finance-5.key49')/*是否汇总*/}
          >
            {getFieldDecorator('summaryFlag', {
              rules: [{ required: false, message: messages('common.please.input')/*请输入*/ }],
              initialValue: record.hasOwnProperty('summaryFlag') ? record.summaryFlag : false
            })(
              <Radio.Group options={[
                { label: messages('common.yes')/*是*/, value: true },
                { label: messages('common.no')/*否*/, value: false }
              ]}/>
            )}
          </Form.Item>
          <Form.Item
            {...formItemLayout}
            label={messages('finance-5.key45')/*科目代码*/}
          >
            {getFieldDecorator('accountCode', {
              rules: [
                { required: true, message: messages('common.please.input')/*请输入*/ },
                { max: 35, message: messages('common.max.characters.length',{arg1: 35})/*最多输入{arg1}个字符*/ }
              ],
              initialValue: record.accountCode
            })(
              <Input disabled={record.hasOwnProperty('id')} placeholder={messages('common.please.input')/*请输入*/}/>
            )}
          </Form.Item>
          <Form.Item
            {...formItemLayout}
            label={messages('finance-5.key46')/*科目名称*/}
          >
            {getFieldDecorator('accountDesc', {
              rules: [{ required: true, message: messages('common.please.input')/*请输入*/ }],
              initialValue: record.accountDesc
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/}/>
            )}
          </Form.Item>
          <Form.Item
            {...formItemLayout}
            label={messages('finance-5.key50')/*余额方向*/}
          >
            {getFieldDecorator('balanceDirection', {
              rules: [{ required: true, message: messages('common.select')/*请选择*/ }],
              initialValue: record.hasOwnProperty('id') ? { key: record.balanceDirection, label: record.balanceDirectionName } : undefined
            })(
              <Selector
                type={'value_list'}
                itemMap
                params={{ type: 2207 }}
              />
            )}
          </Form.Item>
          <Form.Item
            {...formItemLayout}
            label={messages('finance-5.key47')/*科目类型*/}
          >
            {getFieldDecorator('accountType', {
              rules: [{ required: true, message: messages('common.select')/*请选择*/ }],
              initialValue: record.hasOwnProperty('id') ? { key: record.accountType, label: record.accountTypeName } : undefined
            })(
              <Selector
                itemMap
                type={'value_list'}
                params={{ type: 2205 }}
              />
            )}
          </Form.Item>
          <Form.Item
            {...formItemLayout}
            label={messages('finance-5.key51')/*报表类型*/}
          >
            {getFieldDecorator('reportType', {
              initialValue: record.reportType ? { key: record.reportType, label: record.reportTypeName } : undefined
            })(
              <Selector
                itemMap
                type={'value_list'}
                params={{ type: 2206 }}
              />
            )}
          </Form.Item>
          {
            record.hasOwnProperty('id') && (
              <div>
                <h3 className='sub-title'>{messages('finance-5.key52')/*子科目*/}</h3>
                <div>
                  <Button type='primary' onClick={this.handleAdd}>{messages('finance-5.key53')/*添加子科目*/}</Button>
                  <Button onClick={this.handleDelete} style={{ marginLeft: '8px' }} disabled={selectedData.length === 0} loading={deleteLoading}>{messages('common.delete')/*删除*/}</Button>
                </div>
                <AdvancedTable.SimpleTable
                  service={this.service}
                  pagination={{ pageSize: 5, pageSizeOptions: ['5', '10'] }}
                  rowSelection={rowSelection}
                  columns={this.columns}
                  propsLoading={propsLoading}
                  searchForm={[]}
                  onRef={ref => this.tabRef = ref}
                  rowKey='id'
                />
              </div>
            )
          }
          <div className='footer-operate'>
            <Button type='primary' onClick={this.handleSave} loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
            <Button onClick={() => close()}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    tenantInfo: state.login.tenant,
    loginUser: state.login.loginUser
  }
}

export default Form.create()(SubjectDetailRule);
